package com.ruoyi.match.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.match.job.service.HistoryMatchTaskService;
import com.ruoyi.match.match.domain.MatchCollectionDate;
import com.ruoyi.match.match.mapper.MatchCollectionDateMapper;
import com.ruoyi.match.utils.BrowserUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * @author sjz
 * @version 1.0.0
 * @desc
 * @date 2023/11/3 19:47
 **/

@Slf4j
@Component
@RequiredArgsConstructor
public class HistoryMatchTask {

    private final MatchCollectionDateMapper collectionDateMapper;
    private final HistoryMatchTaskService historyMatchTaskService;

    @XxlJob("historyMatchTask")
    private void process() throws IOException {
        LocalDate startDate = LocalDate.now().plusDays(1);
        MatchCollectionDate matchCollectionDate = collectionDateMapper.selectOne(Wrappers.<MatchCollectionDate>lambdaQuery()
            .orderByDesc(MatchCollectionDate::getMatchDate).last("limit 1"));
        if(Objects.nonNull(matchCollectionDate)){
            startDate = DateUtil.toLocalDateTime(matchCollectionDate.getMatchDate()).toLocalDate().plusDays(1);
        }
        LocalDate endDate = LocalDate.now();
        // 获取参数
        String matchDate = XxlJobHelper.getJobParam();
        if(StrUtil.isNotBlank(matchDate)){
            startDate = LocalDate.parse(matchDate, DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        }
        WebDriver browser = BrowserUtil.createBrowser();
        try {
            while (startDate.isBefore(endDate)){
                log.warn("查找比赛日期：{}",startDate.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
                boolean exists = collectionDateMapper.exists(Wrappers.<MatchCollectionDate>lambdaQuery()
                    .eq(MatchCollectionDate::getMatchDate, startDate));
                if(!exists){
                    historyMatchTaskService.getHistoryMatchInfo(browser,startDate);
                    MatchCollectionDate newDate = new MatchCollectionDate();
                    newDate.setMatchDate(DateUtil.parse(startDate.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN))));
                    collectionDateMapper.insert(newDate);
                }
                startDate = startDate.plusDays(1);
            }
        } finally {
            log.warn("浏览器退出");
            browser.quit();
        }


    }
}
